package com.akkainaction.tool.future;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.dispatch.Futures;
import akka.dispatch.Mapper;
import akka.dispatch.OnFailure;
import akka.dispatch.OnSuccess;
import akka.pattern.Patterns;
import akka.util.Timeout;
import com.akkainaction.tool.future.actor.CountActor;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class TestCountActor {

    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create("sys");
        List<String> wordList = Arrays.asList("java", "c++", "Linux");
        Timeout timeout = new Timeout(Duration.create(3, TimeUnit.SECONDS));
        List<Future<Integer>> futureList = new ArrayList<>(wordList.size());
        for (int i = 0; i < wordList.size(); i++) {
            ActorRef countActorRef = system.actorOf(Props.create(CountActor.class), "countActor" + i);
            Future<Integer> future = (Future) Patterns.ask(countActorRef, wordList.get(i), timeout);
            futureList.add(future);
        }
        Future<Iterable<Integer>> fs = Futures.sequence(futureList, system.dispatcher());
        Future<Integer> fv = fs.map(new Mapper<Iterable<Integer>, Integer>() {
            @Override
            public Integer apply(Iterable<Integer> plist) {
                int total = 0;
                for (Integer v : plist) {
                    total += v;
                }
                return total;
            }
        }, system.dispatcher());
        try {
            Integer total = Await.result(fv, timeout.duration());
            System.out.println("统计结果:[" + total + "]");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
